<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <Header @add="addtodo" />
        <List 
          :todos="todos" 
        />
        <Footer 
          :cleartododne="cleartododne"
          :todos="todos"
          :checkAllTodo="checkAllTodo"
        />
      </div>
    </div>
  </div>
</template>

<script>
import Header from '../src/components/Header.vue';
import List from '../src/components/List.vue';
import Footer from '../src/components/Footer.vue';
export default {
  name: "App",
  components:{Header,List,Footer},
  data(){
      return {
          todos:JSON.parse(localStorage.getItem('todos')) ||[] 
      }
  },
  methods: {
    // 增加一个todo
    addtodo(todoObj){
      // 校验数据-是否有同名的todo对象
      const result = this.todos.find(todo => todo.title === todoObj.title)
      if(result){
        // 有同名
        alert('不能重复添加');
        return false;
      }else{
        // 没有同名
        this.todos.unshift(todoObj);
        return true;
      }
    },
    // 删除一个todo
    deletetodo(id){
      // 过滤不想要的todo
      const newtodos = this.todos.filter(todo => todo.id !== id);
      // 更新数据
      this.todos = newtodos;
    },
    // 勾选一个todo
    selectetodo(id,done){
      this.todos.forEach((todo)=>{
        if(todo.id == id){
          todo.done = done;
        }
      })
    },
    // 清除所有已完成项
    cleartododne(){
      // FIXME: 方法一
      // const newtodos = this.todos.filter(todo=> todo.done === false)
      // FIXME: 方法二
      const newtodos = this.todos.filter(todo=> !todo.done)
      this.todos = newtodos
    },
    // 全选
    checkAllTodo(done){
      this.todos.forEach(todo=>todo.done=done)
    }
  },
  watch:{
    todos:{
      deep:true,
      handler(value){
        localStorage.setItem('todos',JSON.stringify(value))
      }
    }
  },
  mounted(){
    this.$bus.$on('delete-one-todo',this.deletetodo);
    this.$bus.$on('select-one-todo',this.selectetodo);
  },
  beforeDestroy() {
    this.$bus.$off(['delete-one-todo','select-one-todo']);
  },
};
</script>

<style>
/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
    0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

</style>